package com.zkw.concurrent.executors

import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future

/**
 * Created by Administrator on 2016/4/8.
 * ExecutorService
 */
class ExecutorServiceMain {
    /*
    * 调度所有线程任务 有任务返回值
    * */
    def exeInvokeAll(){
        ExecutorService singleExe = Executors.newSingleThreadExecutor()
        def callables = new HashSet<Callable<String>>()
        callables.add(new Callable<String>() {
            @Override
            String call() throws Exception {
                return 'all task1'
            }
        })
        callables.add(new Callable<String>() {
            @Override
            String call() throws Exception {
                return 'all task2'
            }
        })

        List<Future<String>> futures = singleExe.invokeAll(callables)
        for (future in futures){
            println future.get()
        }

        singleExe.shutdown()

    }

    /*
    * 随机选取一个线程任务执行 有任务返回值
    * */
    def exeInvokeAny(){
        ExecutorService singleExe = Executors.newSingleThreadExecutor()
        def callables = new HashSet<Callable<String>>()
        callables.add(new Callable<String>(){
            @Override
            String call() throws Exception {
                return 'any task1'
            }
        })
        callables.add(new Callable<String>(){
            @Override
            String call() throws Exception {
                return 'any task2'
            }
        })
        String result = singleExe.invokeAny(callables)
        println('result= '+result)
        singleExe.shutdown
    }

    public static void main(String[] args) {
        println('execut thread pool')
        def test = new ExecutorServiceMain()
//        test.exeInvokeAny()
        test.exeInvokeAll()
    }

}
